﻿using RuTracker.Interface;
using RuTracker.Interface.Editors;
using RuTracker.Interface.Login;
using RuTrackerLib.Editors;

namespace RuTrackerLib.Tracker.RequestProcessors
{
    class SearchRequestProcessor : IRequestProcessor
    {
        public const string SearchTag = "query=";

        private readonly ITrackerAccessor _trackerAccessor;
        private readonly IUserRepository _userRepository;
        private readonly ISessionStorage _sessionStorage;
        private readonly IHtmlEditor[] _editors;

        public SearchRequestProcessor(
            ITrackerAccessor trackerAccessor
            , IUserRepository userRepository
            , ISessionStorage sessionStorage
            , IHtmlEditor[] editors)
        {
            _editors = editors;
            _sessionStorage = sessionStorage;
            _trackerAccessor = trackerAccessor;
            _userRepository = userRepository;
        }

        public RequestProcessingResults ProcessRequest(string query, string userName)
        {
            string searchUrl = query.Replace(SearchTag, string.Empty);
            _sessionStorage.CurrentFolder = WebFolderManager.GetParentFolder(_trackerAccessor.TrackerInfo.SearchUrl);
            return Search(searchUrl, userName);
        }

        private RequestProcessingResults Search(string query, string userName, bool isReloginAttempt = false)
        {
            LoginResults loginResults = _trackerAccessor.Search(query);
            bool isReloginRequired = !loginResults.Succeeded;
            HtmlEditor editor = new HtmlEditor(_editors);

            if (isReloginRequired && !isReloginAttempt)
            {
                User user = _userRepository.GetUser(userName);

                _trackerAccessor.SignIn(user.Name, user.Password);
                return Search(query, userName, true);
            }

            string html = editor.Edit(loginResults.Html);

            return new RequestProcessingResults
                       {
                           Html = html,
                           IsLoginRequired = isReloginRequired,
                       };
        }
    }
}
